import { getInstructionsId, pushProductInfo } from '@/api/product';
import { chat } from '@/api/volcengine';
import { PushState, StateType } from '@/config';
import { TaskInfo } from '@/entrypoints/hook/useConcurrentRequest';
import { useDirectoryHandle } from '@/entrypoints/hook/useDirectoryHandle';
import {
  getImagesFile,
  getInstructionsFile,
  getVideoFile,
  PackageShape,
  PackageType,
  ProductInfo,
  serializeDescription,
  serializeMainProductSkuSpecReqs,
  serializeVariationListStr,
  uploadImage,
  uploadInstructions,
  uploadVideo,
} from '@/lib/dianxiaomi';
import {
  getCollectedGigaProductDetailInfo,
  getProducInfo,
  getProductState,
  saveProductInfo,
  setProductState,
} from '@/lib/filesystem';
import { GigaProductDetialInfo } from '@/lib/giga';
import { getProductTitle } from '@/lib/postme';
import { getLimitedFileName, getVideoMetadata } from '@/lib/utils';
import { useSettingsStore } from '@/store';
import { OperationMessageType } from '@/store/message';
import { toast } from 'sonner';
import { useMessage } from './useDiaoxiaomiMessage';

const pushingProduct: Record<string, boolean> = {};
export function usePush() {
  const { resetMessage, addMessage, resetAndAddMessage } = useMessage();
  const pushSettings = useSettingsStore((state) => state.pushSettings);
  const generatorTitleName = useSettingsStore((state) => state.processSettings.generatorTitleName);
  const allowCharacters = useSettingsStore((state) => state.processSettings.allowCharacters);
  const hotSearch = useSettingsStore((state) => state.processSettings.hotSearch);
  const violateList = useSettingsStore((state) => state.processSettings.violateList);
  const bannerWorldList = useSettingsStore((state) => state.processSettings.bannerWorldList);
  const isRemoveViolateList = useSettingsStore(
    (state) => state.processSettings.isRemoveViolateList,
  );
  const isRemoveBannerWorldList = useSettingsStore(
    (state) => state.processSettings.isRemoveBannerWorldList,
  );
  const isUseAiGenerateTitle = useSettingsStore(
    (state) => state.processSettings.isUseAiGenerateTitle,
  );
  const shopId = useSettingsStore((state) => state.pushSettings.shopId);
  const volcengine = useSettingsStore((state) => state.accountSetting.volcengine);

  const appConfig = useAppConfig();
  const { getDirectoryHandle } = useDirectoryHandle();

  const getSkuIdInfoDirectoryHandle = useCallback(
    async function getSkuIdInfoDirectoryHandle(skuIdInfo: string) {
      const directoryHandle = await getDirectoryHandle();
      const skuIdInfoDirectoryHandle = await directoryHandle.getDirectoryHandle(skuIdInfo, {
        create: false,
      });
      return skuIdInfoDirectoryHandle;
    },
    [getDirectoryHandle],
  );

  const getCategoryInfo = useCallback(
    async (collectedGigaProductDetailInfo: GigaProductDetialInfo) => {
      if (!pushSettings.isUseAiCategory) {
        return {
          categoryId: pushSettings.category.categoryId,
          attributes: pushSettings.category.attributes,
        };
      } else {
        // 获取预配置的产品分类
        const content = [
          `帮我从以下的描述中挑选预设值的产品分类,分类格式严格为: {categoryName: <categoryName>`,
          `产品的名称:${collectedGigaProductDetailInfo.productName}`,
          `产品的特点:${collectedGigaProductDetailInfo.feature?.join(',')}`,
          `下面是分类的名称:${pushSettings.categoryOptionList.map((item) => item.categoryName).join(',')}`,
        ];
        // 从 ai 那里获取分类
        addMessage({
          type: OperationMessageType.info,
          category: collectedGigaProductDetailInfo.skuIdInfo,
          message: '开始让大模型分析产品的类型',
        });
        const chatResult = await chat({
          model: 'doubao-1.5-pro-32k-250115',
          system: 'You are a professional e-commerce product selection specialist.',
          content: content.join('\n'),
          apiKey: volcengine.apiKey,
        });
        try {
          const categoryName = chatResult.choices[0].message.content;
          if (categoryName) {
            addMessage({
              type: OperationMessageType.success,
              category: collectedGigaProductDetailInfo.skuIdInfo,
              message: `大模型分析产品的类型成功: ${categoryName}`,
            });
            // 大模型有可能返回更多的字符串,因此使用包含的方式来匹配
            const categoryItem = pushSettings.categoryOptionList.find((item) =>
              categoryName.includes(item.categoryName),
            );
            if (categoryItem) {
              return {
                categoryId: categoryItem.categoryId,
                attributes: categoryItem.attributes,
              };
            } else {
              throw new Error(
                '大模型分析产品的类型成功,但是分享出的目录名称没有匹配上预设值的产品分类',
              );
            }
          } else {
            throw new Error('大模型分析产品的类型失败');
          }
        } catch (error) {
          throw new Error('大模型分析产品的类型失败');
        }
      }
    },
    [pushSettings, volcengine],
  );

  const getImageUrls = useCallback(
    async (skuIdInfoDirectoryHandle: FileSystemDirectoryHandle, productInfo: ProductInfo) => {
      const imagesDirectoryHandle = await skuIdInfoDirectoryHandle.getDirectoryHandle(
        appConfig.imagesDirectoryname,
        {
          create: true,
        },
      );
      // 读取所有的图像文件,并按照名称进行排序
      const imageFiles = await getImagesFile(imagesDirectoryHandle);

      if (imageFiles.length === 0) {
        // addMessage({
        //   category: productInfo.skuIdInfo,
        //   type: OperationMessageType.error,
        //   message: `轮播图中没有图片`,
        // });
        throw new Error(`轮播图目录中不存在图片`);
      }

      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `开始上传图像到服务器上(需等待一定时间)`,
      });
      const imageUrls = await Promise.all(
        imageFiles.map(async (file) => {
          const imageUrl = await uploadImage(file, productInfo, pushSettings.isUploadToImageSpace);
          addMessage({
            category: productInfo.skuIdInfo,
            type: OperationMessageType.verbose,
            message: `${imageUrl} 图片上传到服务器上`,
          });
          return imageUrl;
        }),
      );
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.success,
        message: `成功上传图像到服务器上`,
      });
      return imageUrls;
    },
    [pushSettings],
  );

  const pushGigaProduct = useCallback(
    async ({
      task,
      productInfo,
      skuIdInfoDirectoryHandle,
      directoryHandle,
    }: {
      task: TaskInfo;
      productInfo: ProductInfo;
      skuIdInfoDirectoryHandle: FileSystemDirectoryHandle;
      directoryHandle: FileSystemDirectoryHandle;
    }) => {
      // 读取已经采集的 giga 产品信息和加工后的产品信息
      // 读取 giga 产品信息
      const collectedGigaProductDetailInfo = await getCollectedGigaProductDetailInfo(
        skuIdInfoDirectoryHandle,
        appConfig.gigaProductDetailInfoFilename,
      );
      if (!collectedGigaProductDetailInfo) {
        throw new Error('发布时无法获取到采集的 giga 产品信息');
      }

      // 填充默认信息或者是非配置的信息
      const prefineProductInfo = {
        skuIdInfo: collectedGigaProductDetailInfo.skuIdInfo,
        gigaSku: collectedGigaProductDetailInfo.gigaSku,
        gigaProductId: collectedGigaProductDetailInfo.gigaProductId,
        // 暂时忽略 id 的设置
        // id: ''
        productId: '0',
        shopId: pushSettings.shopId,
        dxmState: pushSettings.dxmState,
        categoryType: 0,
        fullCid: '4028693-',
        sourceUrl: collectedGigaProductDetailInfo.productUrl,
        productOrigin: pushSettings.productOrigin,
        region2Id: pushSettings.region2Id,
        originFileUrl: '',
        outerGoodsUrl: '',
        sensitiveAttr: '',
        personalizationSwitch: 0 as 0 | 1,
        draftImgUrl: '',
        optionValue: '[]',
        goodsModel: '',
        packageShape: '' as '' | PackageShape,
        packageType: '' as '' | PackageType,
        packageImages: '',
        shipmentLimitSecond: pushSettings.shipmentLimitSecond,
        freightTemplateId: pushSettings.freightTemplateId,
        productSemiManagedReq: '100',
        productWarehouseRouteReq: `[{"warehouseId":"${pushSettings.warehouseId}","siteIdList":["100"]}]`,
        qualifiedEn: '',
        sizeTemplateIds: '',
      };
      // 填充加工的信息
      productInfo = {
        ...productInfo,
        ...prefineProductInfo,
        // productName, productNameI18n 由采集加工生成的标题生成
      };

      // 标题生成
      let title = collectedGigaProductDetailInfo.productName;
      // 是否使用 ai 生成标题
      if (isUseAiGenerateTitle) {
        title = await getProductTitle({
          name: generatorTitleName || directoryHandle.name,
          advantage: collectedGigaProductDetailInfo.feature || [],
          keyWord: collectedGigaProductDetailInfo.productName,
        });
        addMessage({
          type: OperationMessageType.success,
          category: task.skuIdInfo,
          message: '使用 ai 创建新的标题成功',
        });
      }
      // 在生成的标题后添加搜索热词
      let hotSearchTitle = title + hotSearch;
      // console.log(`生成的标题: ${hotSearchTitle}`);
      // 进行违禁词的检测
      if (violateList && violateList.length > 0) {
        const foundViolate = violateList.find((violate) => {
          // console.log(`正在检测违禁词: ${violate}`);
          return hotSearchTitle.includes(violate);
        });
        if (foundViolate) {
          // console.log(`检测到违禁词: ${foundViolate}`); // 调试输出
          if (isRemoveViolateList) {
            // 过滤掉所有违禁词
            violateList.forEach((violate) => {
              hotSearchTitle = hotSearchTitle.replace(violate, '');
            });
          } else {
            throw new Error(`标题中存在违禁词: ${foundViolate}`);
          }
        }
      } else {
        throw new Error('请到加工配置中添加违禁词文件');
      }

      // 进行品牌词检测
      // console.log(bannerWorldList, isRemoveBannerWorldList);
      if (bannerWorldList && bannerWorldList.length > 0) {
        const foundBannerWorld = bannerWorldList.find((bannerWorld) => {
          // console.log(`正在检测违禁词: ${violate}`);
          return hotSearchTitle.includes(bannerWorld);
        });
        if (foundBannerWorld) {
          // console.log(`检测到违禁词: ${foundViolate}`); // 调试输出
          if (isRemoveBannerWorldList) {
            // 过滤掉所有违禁词
            bannerWorldList.forEach((bannerWorld) => {
              hotSearchTitle = hotSearchTitle.replace(bannerWorld, '');
            });
          } else {
            throw new Error(`标题中存在品牌词: ${foundBannerWorld}`);
          }
        }
      }

      // 对最终生成的标题进行过滤,过滤掉中文和表情符号
      hotSearchTitle = [...hotSearchTitle]
        .map((c) => {
          if (allowCharacters.includes(c) || c.match(/[0-9a-zA-Z ]/)) {
            return c;
          } else {
            return '';
          }
        })
        .join('');

      productInfo.productName = hotSearchTitle;
      productInfo.productNameI18n = JSON.stringify({
        en: hotSearchTitle,
      });

      // 产品分类
      const { categoryId, attributes } = await getCategoryInfo(collectedGigaProductDetailInfo);
      // console.log('产品分类', categoryId, attributes);
      productInfo.categoryId = categoryId;
      productInfo.attributes = attributes;

      // 等待图像上传
      const imageUrls: string[] = await getImageUrls(skuIdInfoDirectoryHandle, productInfo);
      productInfo.mainProductSkuSpecReqs = serializeMainProductSkuSpecReqs(productInfo, imageUrls);
      productInfo.mainImage = imageUrls.join('|');
      productInfo.materialImgUrl = imageUrls[0] || '';

      // 处理规格属性
      productInfo.variationListStr = serializeVariationListStr(
        productInfo,
        collectedGigaProductDetailInfo,
        imageUrls,
        pushSettings.priceMultiplyingFactor,
        pushSettings.warehouseId,
      );

      // 处理描述
      productInfo.description = serializeDescription(
        imageUrls,
        collectedGigaProductDetailInfo.feature || [],
        collectedGigaProductDetailInfo.description || [],
      );

      // 等待产品说明书上传
      try {
        const instructionsFile = await getInstructionsFile(
          skuIdInfoDirectoryHandle,
          appConfig.productDetailDirectorname,
        );

        if (instructionsFile || pushSettings.commonProductInstructions) {
          addMessage({
            category: productInfo.skuIdInfo,
            type: OperationMessageType.info,
            message: `开始上传产品说明书到服务器上(需等待一定时间)`,
          });
          let instructionsId = '';
          let instructionsLanguages = '';
          let instructionsName = '';
          let dxmPdfUrl = '';
          let instructionsTranslateId = '';
          let isCommonProductInstructions = false;
          if (instructionsFile) {
            try {
              const instructionsUrl = await uploadInstructions(instructionsFile, productInfo);
              // 需要获取说明书的 id
              const instructionsIdResult = await getInstructionsId(shopId, instructionsUrl);
              if (instructionsIdResult.code !== 0) {
                throw new Error(`无法获取到上传后的产品说明书的 id: ${instructionsIdResult.msg}`);
              }
              instructionsId = instructionsIdResult.data.instructionsId;
              instructionsLanguages = instructionsIdResult.data.instructionsLanguages || 'en';
              instructionsName = instructionsFile.name;
              dxmPdfUrl = instructionsUrl;
            } catch (error) {
              // 记录 productInfo 内容到 product.info 文件中
              // throw new Error(`上传产品说明书到服务器上失败: ${(error as Error).message}`);
              // 使用通用的产品说明书进行上传
              isCommonProductInstructions = true;
            }
          } else {
            isCommonProductInstructions = true;
          }
          if (isCommonProductInstructions) {
            const res = await fetch(pushSettings.commonProductInstructions);
            const blob = await res.blob();
            const file = new File([blob], 'tongyong.pdf', { type: blob.type });
            const instructionsUrl = await uploadInstructions(file, productInfo);
            // 需要获取说明书的 id
            const instructionsIdResult = await getInstructionsId(shopId, instructionsUrl);
            if (instructionsIdResult.code !== 0) {
              throw new Error(`无法获取到上传后的产品说明书的 id: ${instructionsIdResult.msg}`);
            }
            instructionsId = instructionsIdResult.data.instructionsId;
            instructionsLanguages = instructionsIdResult.data.instructionsLanguages || 'en';
            instructionsName = file.name;
            dxmPdfUrl = instructionsUrl;
          }
          productInfo.instructionsId = instructionsId;
          productInfo.instructionsLanguages = instructionsLanguages;

          // 对说明书的文件名称的大小进行限制,保证在 25 个字符内
          productInfo.instructionsName = getLimitedFileName(instructionsName, 20);
          productInfo.dxmPdfUrl = dxmPdfUrl;
          productInfo.instructionsTranslateId = instructionsTranslateId;
          addMessage({
            category: productInfo.skuIdInfo,
            type: OperationMessageType.success,
            message: `成功上传产品说明书到服务器上`,
          });
        }
      } catch (error) {
        // 如果在上传通用产品说明书时发生错误,那么将终止上传
        addMessage({
          category: productInfo.skuIdInfo,
          type: OperationMessageType.info,
          message: `上传通用产品说明书时发生错误,不再上传产品说明书: ${(error as Error).message}`,
        });
      }

      // 等待视频上传
      const videoFile = await getVideoFile(
        skuIdInfoDirectoryHandle,
        appConfig.productVideoDirectorname,
      );
      if (videoFile) {
        try {
          addMessage({
            category: productInfo.skuIdInfo,
            type: OperationMessageType.info,
            message: `开始上传产品视频到服务器上(需等待一定时间)`,
          });

          let videoUrl = '';

          // 对视频的规则进行处理
          const metadata = await getVideoMetadata(videoFile);
          const { duration, width, height } = metadata;
          const ratio = width / height;
          if (duration > 60) {
            addMessage({
              category: productInfo.skuIdInfo,
              type: OperationMessageType.info,
              message: `当前视频的时长(${duration})大于 60 秒,终止视频上传`,
            });
          } else if (
            Math.abs(ratio - 4 / 3) > 0.01 &&
            Math.abs(ratio - 1) > 0.01 &&
            Math.abs(ratio - 16 / 9) > 0.01
          ) {
            addMessage({
              category: productInfo.skuIdInfo,
              type: OperationMessageType.info,
              message: `当前视频的比例为(${ratio}),不符合 1:1,3:4,16:9 的比例,终止视频上传`,
            });
          } else {
            videoUrl = await uploadVideo(videoFile, productInfo, pushSettings.isUploadToImageSpace);
            addMessage({
              category: productInfo.skuIdInfo,
              type: OperationMessageType.success,
              message: `成功上传视频到服务器上`,
            });
          }

          productInfo.videoUrl = videoUrl;
          productInfo.videoThumbnail = '';
        } catch (error) {
          // 记录 productInfo
          saveProductInfo({
            productInfo: productInfo,
            productInfoFilename: appConfig.productInfoFilename,
            skuIdInfoDirectoryHandle,
          });
          // 记录 productInfo 内容到 product.info 文件中
          throw new Error(`上传视频到服务器上失败: ${(error as Error).message}`);
        }
      }

      return productInfo;
    },
    [
      pushSettings,
      generatorTitleName,
      allowCharacters,
      hotSearch,
      violateList,
      isRemoveViolateList,
      bannerWorldList,
      isRemoveBannerWorldList,
      shopId,
      getCategoryInfo,
      getImageUrls,
      isUseAiGenerateTitle,
    ],
  );

  const pushProduct = useCallback(
    async function pushProduct(task: TaskInfo) {
      const { skuIdInfo, gigaProductId, gigaSku, available, force = false } = task;
      if (pushingProduct[skuIdInfo]) {
        toast.info(`货号 ${skuIdInfo} 正在上传中`);
        return;
      }

      pushingProduct[skuIdInfo] = true;

      const directoryHandle = await getDirectoryHandle();

      // 创建货号目录
      const skuIdInfoDirectoryHandle = await getSkuIdInfoDirectoryHandle(skuIdInfo).catch(
        (error) => {
          pushingProduct[skuIdInfo] = false;
          throw error;
        },
      );
      try {
        addMessage({
          type: OperationMessageType.info,
          category: skuIdInfo,
          message: '开始上传产品',
        });
        toast.info(`${skuIdInfo}: 上传开始`);

        if (!force) {
          const state = await getProductState(
            appConfig.productStateFilename,
            skuIdInfoDirectoryHandle,
          );
          if (state.pushState === PushState.success) {
            addMessage({
              category: skuIdInfo,
              type: OperationMessageType.success,
              message: `该产品已经上传过了 ${doneMessage}`,
            });
            toast.success(`${skuIdInfo}: 已经上传过了`);
            pushingProduct[skuIdInfo] = false;
            return;
          }
        }

        let productInfo = {} as ProductInfo;

        // 开始解析 productInfo 的所有信息
        productInfo = await pushGigaProduct({
          task,
          productInfo,
          skuIdInfoDirectoryHandle,
          directoryHandle,
        });

        // 保存 productInfo
        await saveProductInfo({
          productInfo: productInfo,
          productInfoFilename: appConfig.productInfoFilename,
          skuIdInfoDirectoryHandle,
        });
        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.info,
          message: `保存 productInfo 信息到本地磁盘成功`,
        });

        const pushResult = await pushProductInfo(productInfo);
        if (pushResult.code !== 0) {
          throw new Error(`${pushResult.msg}`);
        }

        // 创建上传完成的状态
        await setProductState(
          {
            [StateType.push]: PushState.success,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );
        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.success,
          message: `上传产品成功 ${doneMessage}`,
          data: {
            kind: '产品信息',
            data: productInfo,
          },
        });
        toast.success(`${skuIdInfo}: 上传成功`);

        pushingProduct[skuIdInfo] = false;
      } catch (error) {
        // 创建采集失败的状态
        await setProductState(
          {
            [StateType.push]: PushState.error,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );

        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.error,
          message: `上传产品失败(请确保填写了相关账号信息): ${(error as Error).message}`,
        });
        pushingProduct[skuIdInfo] = false;
      }
    },
    [getSkuIdInfoDirectoryHandle, pushGigaProduct],
  );

  const pushProductVideo = useCallback(
    async function pushProductVideo(task: TaskInfo) {
      const { skuIdInfo, gigaProductId, gigaSku, available, force = false } = task;
      if (pushingProduct[skuIdInfo]) {
        toast.info(`货号 ${skuIdInfo} 正在上传中`);
        return;
      }

      pushingProduct[skuIdInfo] = true;

      const directoryHandle = await getDirectoryHandle();

      // 创建货号目录
      const skuIdInfoDirectoryHandle = await getSkuIdInfoDirectoryHandle(skuIdInfo).catch(
        (error) => {
          pushingProduct[skuIdInfo] = false;
          throw error;
        },
      );
      try {
        const productInfo = await getProducInfo(
          skuIdInfoDirectoryHandle,
          appConfig.productInfoFilename,
        );
        if (!productInfo) {
          throw new Error(`无法获取到 product 产品信息`);
        }
        const videoFile = await getVideoFile(
          skuIdInfoDirectoryHandle,
          appConfig.productVideoDirectorname,
        );
        if (videoFile) {
          if (!force) {
            const state = await getProductState(
              appConfig.productStateFilename,
              skuIdInfoDirectoryHandle,
            );
            if (state.pushState === PushState.success) {
              addMessage({
                category: skuIdInfo,
                type: OperationMessageType.success,
                message: `该产品已经上传过了 ${doneMessage}`,
              });
              toast.success(`${skuIdInfo}: 已经上传过了`);
              pushingProduct[skuIdInfo] = false;
              return;
            }
          }
          addMessage({
            category: skuIdInfo,
            type: OperationMessageType.info,
            message: `开始上传产品视频到服务器上(需等待一定时间)`,
          });
          let videoUrl = '';
          try {
            // 对视频的规则进行处理
            const metadata = await getVideoMetadata(videoFile);
            const { duration, width, height } = metadata;
            const ratio = width / height;
            if (duration > 60) {
              addMessage({
                category: productInfo.skuIdInfo,
                type: OperationMessageType.info,
                message: `当前视频的时长(${duration})大于 60 秒,终止视频上传`,
              });
            } else if (
              Math.abs(ratio - 3 / 4) > 0.01 &&
              Math.abs(ratio - 1) > 0.01 &&
              Math.abs(ratio - 16 / 9) > 0.01
            ) {
              addMessage({
                category: productInfo.skuIdInfo,
                type: OperationMessageType.info,
                message: `当前视频的比例为(${ratio}),不符合 1:1,3:4,16:9 的比例,终止视频上传`,
              });
            } else {
              videoUrl = await uploadVideo(
                videoFile,
                productInfo,
                pushSettings.isUploadToImageSpace,
              );
              addMessage({
                category: productInfo.skuIdInfo,
                type: OperationMessageType.success,
                message: `成功上传视频到服务器上`,
              });
            }
          } catch (error) {
            throw new Error(`上传视频到服务器上失败: ${(error as Error).message}`);
          }

          productInfo.videoUrl = videoUrl;
          productInfo.videoThumbnail = '';

          // 这里还有上传产品的操作
          // 保存 productInfo
          await saveProductInfo({
            productInfo: productInfo,
            productInfoFilename: appConfig.productInfoFilename,
            skuIdInfoDirectoryHandle,
          });
          addMessage({
            category: skuIdInfo,
            type: OperationMessageType.info,
            message: `保存 productInfo 信息到本地磁盘成功`,
          });

          // 发布产品
          await pushProductInfo(productInfo);
        } else {
          addMessage({
            category: skuIdInfo,
            type: OperationMessageType.info,
            message: `没有找到该产品的视频信息,无需上传视频`,
          });
        }
        // 创建上传完成的状态
        await setProductState(
          {
            [StateType.push]: PushState.success,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );
        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.success,
          message: `上传产品成功 ${doneMessage}`,
          data: {
            kind: '产品信息',
            data: productInfo,
          },
        });
        toast.success(`${skuIdInfo}: 上传成功`);

        pushingProduct[skuIdInfo] = false;
      } catch (error) {
        await setProductState(
          {
            [StateType.push]: PushState.error,
          },
          appConfig.productStateFilename,
          skuIdInfoDirectoryHandle,
        );

        addMessage({
          category: skuIdInfo,
          type: OperationMessageType.error,
          message: `上传产品失败: ${(error as Error).message}`,
        });
        pushingProduct[skuIdInfo] = false;
      }
    },
    [getSkuIdInfoDirectoryHandle, pushGigaProduct],
  );

  return {
    pushProduct,
    pushProductVideo,
  };
}
